<template>
  <view class="home-content">
    <scroll-view
      scroll-y="true"
      class="home-scroll"
      refresher-enabled="true"
      :refresher-triggered="triggered"
      :refresher-threshold="100"
      @refresherpulling="onPulling"
      @refresherrefresh="onRefresh"
      @refresherrestore="onRestore"
      @refresherabort="onAbort"
    >
      <!-- 推荐用户卡片 -->
      <view @click="toRecommendAction" class="recommended_users">
        <view class="recommended_users_text">
          <view class="recommended_users_title">分配对象啦~</view>
          <view class="recommended_users_line"
            >快来看看专门为你定制的对象吧</view
          >
          <view class="recommended_users_line">据说这里牵手成功率最高哦</view>
        </view>
        <view class="recommended_users_img">
          <image
            v-for="(item, index) in recommended_users"
            :key="index"
            :src="item"
          ></image>
        </view>
      </view>
      <!-- 中间导航栏 -->
      <view class="nav">
        <view @click="navItemAction(0)" class="nav_item">
          <image src="../../../static/images/home/nav_3.png" mode=""></image>
          <text>单身活动</text>
        </view>
        <view @click="navItemAction(1)" class="nav_item">
          <image src="../../../static/images/home/nav_4.png" mode=""></image>
          <text>情侣约会</text>
        </view>
        <view @click="navItemAction(2)" class="nav_item">
          <image src="../../../static/images/home/nav_1.png" mode=""></image>
          <text>形象设计</text>
        </view>
        <view @click="navItemAction(3)" class="nav_item">
          <image src="../../../static/images/home/nav_2.png" mode=""></image>
          <text>情感顾问</text>
        </view>
      </view>
      <!-- 通知 -->
      <!-- <view v-if="gifts.length > 0" class="message">
				<image class="flower" src="../../../static/images/home/heart.png" mode=""></image>
				<text class="text">
					{{gifts[0].from_user_name || "匿名"}}给@{{gifts[0].to_user_name || "匿名"}}
					<text class="text_red">{{gifts[0].count || 0 }}朵玫瑰花</text>
				</text>
				<image class="heart" src="../../../static/images/home/flower.png" mode=""></image>
			</view> -->
      <view v-if="gifts.length > 0" class="message-notice">
        <mnoticebar bg-color="#FFFFFF" :list="gifts"></mnoticebar>
      </view>
      <!-- 列表 -->
      <view class="list" :style="'height: ' + loadingTop + 'rpx'">
        <view class="ad">
          <image src="../../../static/images/home/ad_bg.png"></image>
          <view class="text">
            <view>如何拍出大片效果</view>
            <view>恋爱第一步，突破形象改造</view>
          </view>
        </view>

        <view
          class="list_item"
          v-for="(item) in lists"
          :key="item._id"
          :class="positionList[item._id].right ? 'right' : 'left'"
          :style="{
            top: positionList[item._id].top + 'rpx',
            width: viewWidth + 'rpx',
            height: positionList[item._id].height + 'rpx',
          }"
          @click="toDetail(item)"
        >
          <view
            class="img"
            :style="{
              width: viewWidth + 'rpx',
              height: positionList[item._id].imageHeight + 'rpx',
            }"
          >
            <image
              :style="{
                width: viewWidth + 'rpx',
                height: positionList[item._id].imageHeight + 'rpx',
              }"
              :id="item._id"
              @load="onImageLoad"
              :src="getImgStr(item)"
              mode="aspectFill"
            ></image>
            <view class="uicon" v-show="isvideo(item)">
              <image src="@/static/images/home/post_video.png"></image>
            </view>
          </view>
          <view class="title">{{ item.note || "" }}</view>
          <view class="bottom">
            <view class="left">
              <image
                @click.stop="toPersionHomeAction(item)"
                mode="aspectFit"
                :src="
                  item.user_info.avatar ||
                  'http://static.kuaimayoupin.com/5814340611455953.png'
                "
              ></image>
            </view>
            <view class="center">
              <view class="name">{{ item.user_info.nick_name || "--" }}</view>
              <view class="info">
                <text>{{ getAges(item.user_info) }}</text>
                <text>{{ item.user_info.native_place || "未知" }}</text>
              </view>
            </view>
            <view @click.stop="praiseAction(item)" class="right">
              <image :src="getAixin(item)"></image>
              <text>{{ item.like_count || 20 }}</text>
            </view>
          </view>
        </view>
      </view>
      <view class="bottom-space"></view>
    </scroll-view>
  </view>
</template>

<script>
import { EventBus } from "@/util/event-bus.js";
import { getAges } from "@/util/tool.js";
import {
  homeConnentRecommend,
  statistics,
  giveLike,
  getGiftsRecentRequest,
  recommendUsers,
} from "@/api/home/home.js";
import mnoticebar from "@/components/notice/column-notice.vue";
const defaultData = {
  // 起始距离（rpx）
  startTop1: 174,
  startTop2: 14,
  // 除了图片和标题以外的高度（rpx）
  contentHeight: 104,
  // 瀑布流容器宽度（rpx）
  viewWidth: 350,
  // 标题可显示宽度（rpx）
  titleWidth: 312,
  // 标题文字大小（rpx）
  titleSize: 26,
  titleLineHeight: 40,
  // 容器之间的间隔Y轴（rpx）
  viewSpace: 20,
  // 列表ID参数名称
  idName: "_id",
  // 列表标题参数名称
  titleName: "note",
  itemHeight: 104 + 28,
};
let allow = true;
// 文字换行计算行数
function drawtext(text, maxWidth) {
  let textArr = text.split("");
  let len = textArr.length;
  // 上个节点
  let previousNode = 0;
  // 记录节点宽度
  let nodeWidth = 0;
  // 文本换行数组
  let rowText = [];
  // 如果是字母，侧保存长度
  let letterWidth = 0;
  // 汉字宽度
  let chineseWidth = defaultData.titleSize;
  // otherFont宽度
  let otherWidth = defaultData.titleSize / 2;
  for (let i = 0; i < len; i++) {
    if (/[\u4e00-\u9fa5]|[\uFE30-\uFFA0]/g.test(textArr[i])) {
      if (letterWidth > 0) {
        if (nodeWidth + chineseWidth + letterWidth * otherWidth > maxWidth) {
          rowText.push({
            type: "text",
            content: text.substring(previousNode, i),
          });
          previousNode = i;
          nodeWidth = chineseWidth;
          letterWidth = 0;
        } else {
          nodeWidth += chineseWidth + letterWidth * otherWidth;
          letterWidth = 0;
        }
      } else {
        if (nodeWidth + chineseWidth > maxWidth) {
          rowText.push({
            type: "text",
            content: text.substring(previousNode, i),
          });
          previousNode = i;
          nodeWidth = chineseWidth;
        } else {
          nodeWidth += chineseWidth;
        }
      }
    } else {
      if (/\n/g.test(textArr[i])) {
        rowText.push({
          type: "break",
          content: text.substring(previousNode, i),
        });
        previousNode = i + 1;
        nodeWidth = 0;
        letterWidth = 0;
      } else if (textArr[i] == "\\" && textArr[i + 1] == "n") {
        rowText.push({
          type: "break",
          content: text.substring(previousNode, i),
        });
        previousNode = i + 2;
        nodeWidth = 0;
        letterWidth = 0;
      } else if (/[a-zA-Z0-9]/g.test(textArr[i])) {
        letterWidth += 1;
        if (nodeWidth + letterWidth * otherWidth > maxWidth) {
          rowText.push({
            type: "text",
            content: text.substring(previousNode, i + 1 - letterWidth),
          });
          previousNode = i + 1 - letterWidth;
          nodeWidth = letterWidth * otherWidth;
          letterWidth = 0;
        }
      } else {
        if (nodeWidth + otherWidth > maxWidth) {
          rowText.push({
            type: "text",
            content: text.substring(previousNode, i),
          });
          previousNode = i;
          nodeWidth = otherWidth;
        } else {
          nodeWidth += otherWidth;
        }
      }
    }
  }
  if (previousNode < len) {
    rowText.push({
      type: "text",
      content: text.substring(previousNode, len),
    });
  }
  return rowText.length;
}
export default {
  components: {
    mnoticebar,
  },
  data() {
    return {
      sessionKey: "",
      openid: "",
      header: {
        top: 0,
        height: 0,
        allHeight: 0,
      },
      isShow: true,
      isFirst: false,
      lists: [],
      positionList: {},
      loadingTop: 0,
      _freshing: false,
      triggered: false,
      gifts: [],
      viewWidth: 350,
      recommended_users: [],
    };
  },
  created() {
    let that = this;
    EventBus.$on("loginSuccess", function (res) {
      that.getHomeList();
    });
    EventBus.$on("likeAction", function (res) {
      console.log("likeAction-------", res);
      that.refreshItemStatus(res);
    });
  },
  mounted() {
    // this.getCalculationPosition();
    this.getHomeList();
    this._freshing = false;
    this.triggered = true;
  },
  methods: {
    onPulling(e) {},
    onRefresh() {
      if (this._freshing) return;
      this._freshing = true;
      this.getHomeList();
    },
    onRestore() {
      this.triggered = "restore";
    },
    onAbort() {},
    getAges(user) {
      let userInfo = user || {};
      let birthdayStr = userInfo.birthday || "";
      if (birthdayStr === "") {
        return "";
      }
      return getAges(birthdayStr);
    },
    getData() {},
    toRecommendAction() {
      this.$emit("toTag", 1);
    },
    getImgStr(item) {
      let pics = item.pic_urls || [];
      let video_url = item.video_url || "";
      if (pics.length > 0) {
        return pics[0];
      } else if (video_url.length > 0) {
        return video_url + "?vframe/jpg/offset/0";
      } else {
        // return item.user_info.avatar || ""
      }
    },
    isvideo(item) {
      let pics = item.pic_urls || [];
      let video_url = item.video_url || "";
      if (pics.length === 0 && video_url.length != "") {
        return true;
      }
      return false;
    },
    // 获取 首页列表
    getHomeList(cb) {
      let that = this;
      // 首页列表数据
      console.log("首页列表数据---start");
      homeConnentRecommend({ limit: 60 }).then(
        (res) => {
          this.triggered = false;
          this._freshing = false;
          console.log("首页列表数据------talkingTip/home--------", res);
          if (res.status == 1) {
            // const oldList = [...that.lists];
            // let newList = res.data.concat(oldList);
            that.lists = res.data;
            // that.lists = newList;
            console.log('首页列表数据------newList--------', newList);
            that.getCalculationPosition();
          } else {
            uni.showToast({
              title: res.message,
              duration: 2000,
            });
          }
		  cb && cb();
        },
        (err) => {
          this.triggered = false;
          this._freshing = false;
          uni.showToast({
            title: err.message,
            duration: 2000,
          });
          console.log("首页列表数据---error", err);
        }
      );
      this.getStatistics();
      this.getGiftsRecent();
      this.getRecommend();
    },
    // 获取 推荐列表
    getRecommend() {
      recommendUsers().then((res) => {
        if (res.status == 1) {
          let recommendList = res.data.forUser;
          let lists = [];
          recommendList.map((user, index) => {
            if (index <= 4) {
              lists.push(user.userinfo.avatar);
            }
          });
          this.recommended_users = lists;

          console.log("recommended_users-------", this.recommended_users);
        }
      });
    },
    getStatistics() {
      statistics().then((res) => {
        console.log("statistics------", res.data);
      });
    },
    getGiftsRecent() {
      getGiftsRecentRequest().then((res) => {
        console.log("首页---getGiftsRecent------", res.data);
        if (res.status == 1) {
          this.gifts = res.data;
          if (this.gifts.length <= 1) {
            this.gifts = this.gifts.concat(res.data);
          }
        }
      });
    },
    // 关闭弹框
    close_layer() {
      // this.isShow = false
    },
    // 节流
    throttle(callback, time = 400) {
      if (!allow) return false;
      allow = false;
      setTimeout(function () {
        allow = true;
        callback();
      }, time);
    },
    // 获取数据位置信息 top,right
    getCalculationPosition() {
      let leftHistoryTop = defaultData.startTop1;
      let rightHistoryTop = defaultData.startTop2;
      let positionList = this.positionList;
      this.lists.forEach((item, index) => {
        let currentHeight = defaultData.contentHeight;
        let positionItem = {};
        // 查看是否有位置数据
        if (positionList[item[defaultData.idName]]) {
          positionItem = positionList[item[defaultData.idName]];
        } else {
          positionList[item[defaultData.idName]] = {};
        }
        // 查看是否有图片高度数据，没有默认等宽
        if (positionItem.imageHeight) {
          currentHeight += positionItem.imageHeight;
          positionList[item[defaultData.idName]].imageLoad = true;
        } else {
          currentHeight += this.viewWidth;
        }
        // 查看是否有标题高度数据，没有获取高度
        // if (positionItem.titleHeight) {
        // 	currentHeight += positionItem.titleHeight;
        // } else {
        let note = item.note || "";
        if (note === "") {
          positionList[item[defaultData.idName]].titleHeight = 0;
        } else {
          let titleListLen = drawtext(
            item[defaultData.titleName],
            defaultData.titleWidth
          );
          let titleHeight =
            (titleListLen >= 2 ? 2 : 1) * defaultData.titleLineHeight;
          positionList[item[defaultData.idName]].titleHeight = titleHeight;
          currentHeight += titleHeight;
        }
        // }
        currentHeight += 20;
        if (leftHistoryTop > rightHistoryTop) {
          positionList[item[defaultData.idName]].top = rightHistoryTop;
          positionList[item[defaultData.idName]].right = true;
          positionList[item[defaultData.idName]].height = currentHeight;
          rightHistoryTop += currentHeight + defaultData.viewSpace;
        } else {
          positionList[item[defaultData.idName]].top = leftHistoryTop;
          positionList[item[defaultData.idName]].right = false;
          positionList[item[defaultData.idName]].height = currentHeight;
          leftHistoryTop += currentHeight + defaultData.viewSpace;
        }
      });
      if (leftHistoryTop > rightHistoryTop) {
        this.loadingTop = leftHistoryTop;
      } else {
        this.loadingTop = rightHistoryTop;
      }
      this.positionList = positionList;
      this.$forceUpdate();
    },
    // 图片加载完成
    onImageLoad(e) {
      let id = e.currentTarget.id;
      let scale = this.viewWidth / e.detail.width;
      let height = scale * e.detail.height;
      if (height > 450 * 4) {
        height = 450 * 4;
      }
      if (this.positionList[id]) {
        this.positionList[id].imageHeight = height;
      } else {
        this.positionList[id] = {
          imageHeight: height,
        };
      }
      // 图片加载完刷新位置节流一下，提升性能
      this.throttle(() => {
        this.getCalculationPosition();
      }, 100);
    },
    getAixin(item) {
      if (item.has_give_like == true) {
        return "../../../static/images/home/aixin.png";
      } else {
        return "../../../static/images/home/laud1.png";
      }
    },
    toDetail(data) {
      let url =
        "/pages/home/detial/detial?trendsId=" +
        (data._id || "") +
        "&userId=" +
        (data.userId || "");
      uni.navigateTo({
        url: url,
      });
    },
    toPersionHomeAction(item) {
      let userId = item.userId ?? "";
      let url = "/pageA/homepage/homepage?user_id=" + userId;
      uni.navigateTo({
        url: url,
      });
    },
    videoClick() {},
    refreshItemStatus(res) {
      this.lists.map((item, index) => {
        if (item._id == res._id) {
          item.has_give_like = res.has_give_like;
          if (res.has_give_like == true) {
            item.like_count += 1;
          } else {
            item.like_count -= 1;
          }
        }
      });
    },
    // 点赞
    praiseAction(item) {
      if (!this.getIsLogin()) {
        this.$emit("toLogin");
        return;
      }
      giveLike({
        id: item._id || "",
        like: !(item.has_give_like || false),
      }).then(
        (res) => {
          if (res.status == 1) {
            if (item.has_give_like || false) {
              item.like_count -= 1;
            } else {
              item.like_count += 1;
              uni.showToast({
                title: "我喜欢你点赞的样子哦",
                icon: "none",
              });
            }
            item.has_give_like = !(item.has_give_like || false);
          }
        },
        (err) => {}
      );
    },
    navItemAction(index) {
      //同一跳转商城首页
      uni.switchTab({
        url: "/pages/mall/mall",
      });
      /* uni.navigateTo({
					url: '/pageA/search-result/search-result?localType=2&localName='+index
				}); */
    },
    getIsLogin() {
      if (uni.getStorageSync("token")) {
        return true;
      }
      return false;
    },
  },
};
</script>

<style scoped lang="scss">
* {
  box-sizing: border-box;
}

.home-content {
  height: 100%;

  .home-scroll {
    .bottom-space {
      height: 20rpx;
      width: 100%;
    }

    background-color: #ffffff;
    height: 100%;

    .recommended_users {
      display: flex;
      padding: 0 28rpx;
      position: relative;
      margin: 0 auto;
      margin-top: 23rpx;
      width: 710rpx;
      height: 200rpx;
      background: linear-gradient(
        347deg,
        rgba(248, 212, 87, 1) 0%,
        rgba(254, 21, 194, 1) 100%
      );
      border-radius: 10rpx;
      color: #fff;

      .recommended_users_text {
        .recommended_users_title {
          padding-top: 44rpx;
          font-size: 30rpx;
          line-height: 42rpx;
          margin-bottom: 10rpx;
        }

        .recommended_users_line {
          padding-top: 4rpx;
          font-size: 26rpx;
          line-height: 36rpx;
        }
      }

      .recommended_users_img {
        position: relative;
        padding-top: 112rpx;
        margin-left: 24rpx;
        flex: 1;

        image {
          width: 66rpx;
          height: 66rpx;
          position: absolute;
          border-radius: 33rpx;
        }

        image:nth-child(5) {
          left: 0rpx;
        }

        image:nth-child(4) {
          left: 46rpx;
        }

        image:nth-child(3) {
          left: 98rpx;
        }

        image:nth-child(2) {
          left: 142rpx;
        }

        image:nth-child(1) {
          left: 188rpx;
        }
      }
    }

    .recommended_users::before {
      position: absolute;
      content: "";
      width: 0;
      height: 0;
      top: -18rpx;
      left: 124rpx;
      /* background: #FE15C2; */

      border-top: 0rpx solid #fe15c2;
      border-bottom: 18rpx solid #fe15c2;
      border-left: 14rpx solid transparent;
      border-right: 14rpx solid transparent;
    }

    .nav {
      width: 710rpx;
      height: 158rpx;
      margin: 0 auto;
      margin-top: 20rpx;
      display: flex;
      justify-content: space-around;
      align-items: center;
      box-shadow: 0px 6px 20px 0px rgba(0, 42, 64, 0.07);
      border-radius: 12px;
      margin-bottom: 10px;
      .nav_item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        image {
          width: 72rpx;
          height: 72rpx;
        }

        text {
          padding-top: 10rpx;
          font-size: 26rpx;
          line-height: 36rpx;
        }
      }
    }

    .message-notice {
      width: 700rpx;
      margin: 20rpx 0 30rpx 0;
    }

    // .message {
    // 	display: flex;
    // 	align-items: center;
    // 	width: 710rpx;
    // 	margin: 30rpx auto 32rpx auto;

    // 	.flower {
    // 		width: 32rpx;
    // 		height: 32rpx;
    // 	}

    // 	.heart {
    // 		width: 30rpx;
    // 		height: 30rpx;
    // 	}

    // 	.text {
    // 		font-size: 26rpx;
    // 		color: #8389a0;
    // 		line-height: 36rpx;
    // 		margin: 0 10rpx;
    // 	}

    // 	.text_red {
    // 		color: #ff5998;
    // 	}
    // }

    .water-flow-container {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }

    .list {
      position: relative;
    }

    .list .list_item.left {
      left: 10px;
    }

    .list .list_item.right {
      right: 10px;
    }

    .ad {
      position: relative;
      break-inside: avoid;
      width: 344rpx;
      height: 176rpx;
      margin-top: -14rpx;
      margin-left: 20rpx;

      image {
        margin-left: -20rpx;
        width: 384rpx;
        height: 190rpx;
      }

      .text {
        position: absolute;
        top: 38rpx;
        left: 20rpx;
        font-size: 26rpx;
        line-height: 40rpx;
      }
    }

    .list_item {
      position: absolute;
      width: 344rpx;
      box-shadow: 0px 6px 20px 0px rgba(0, 42, 64, 0.07);
      border-radius: 12px;
      margin-bottom: 24rpx;
      overflow: hidden;
      box-sizing: border-box;

      .img {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        .uicon {
          position: absolute;
          top: 16rpx;
          right: 16rpx;
          z-index: 10;
          image {
            width: 46rpx;
            height: 36rpx;
          }
        }
      }

      .title {
        margin: 14rpx 16rpx;
        box-sizing: border-box;
        text-overflow: -o-ellipsis-lastline;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        font-size: 26rpx;
      }

      .bottom {
        display: flex;
        align-items: center;
        height: 104rpx;
        box-sizing: border-box;

        .left {
          margin: 0 14rpx;
          width: 60rpx;
          height: 60rpx;
          overflow: hidden;
          border-radius: 50%;

          image {
            width: 60rpx;
            height: 60rpx;
          }
        }

        .center {
          flex: 1;

          .name {
            height: 36rpx;
            font-size: 26rpx;
            font-weight: 500;
            line-height: 36rpx;
          }

          .info {
            font-size: 22rpx;
            color: #8389a0;
            line-height: 32rpx;
          }
        }

        .right {
          width: 76rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          font-size: 22rpx;
          color: #8389a0;
          line-height: 32rpx;

          image {
            width: 44rpx;
            height: 40rpx;
          }
        }
      }
    }
  }
}
</style>
